import { db } from '../client';
import { sysUser, sysRole, sysUserRole, sysMenu } from '../schema/index';
import { eq, and } from 'drizzle-orm';
import * as bcrypt from 'bcrypt';
import { MENU_TYPE, SYSTEM_ROLE } from '@nbase/shared';

/**
 * 菜单数据结构
 */
interface MenuData {
  name: string;
  permission: string;
  type: number;
  sort: number;
  path?: string | null;
  icon?: string | null;
  component?: string | null;
  visible: boolean;
  keepAlive: boolean;
  children?: MenuData[];
}

/**
 * 菜单数据定义
 */
const menuData: MenuData[] = [
  {
    name: '首页',
    permission: 'home',
    type: MENU_TYPE.MENU,
    sort: 1,
    path: '/',
    icon: 'HomeOutlined',
    component: 'Home',
    visible: true,
    keepAlive: true,
  },
  {
    name: '系统管理',
    permission: 'system',
    type: MENU_TYPE.MENU,
    sort: 2,
    path: '/system',
    icon: 'SettingOutlined',
    component: null,
    visible: true,
    keepAlive: false,
    children: [
      {
        name: '用户管理',
        permission: 'system:user',
        type: MENU_TYPE.MENU,
        sort: 1,
        path: '/system/user',
        icon: 'TeamOutlined',
        component: 'System/User',
        visible: true,
        keepAlive: true,
        children: [
          { name: '查询', permission: 'system:user:query', type: MENU_TYPE.BUTTON, sort: 1, visible: true, keepAlive: false },
          { name: '新增', permission: 'system:user:create', type: MENU_TYPE.BUTTON, sort: 2, visible: true, keepAlive: false },
          { name: '修改', permission: 'system:user:update', type: MENU_TYPE.BUTTON, sort: 3, visible: true, keepAlive: false },
          { name: '删除', permission: 'system:user:delete', type: MENU_TYPE.BUTTON, sort: 4, visible: true, keepAlive: false },
        ],
      },
      {
        name: '角色管理',
        permission: 'system:role',
        type: MENU_TYPE.MENU,
        sort: 2,
        path: '/system/role',
        icon: 'SafetyOutlined',
        component: 'System/Role',
        visible: true,
        keepAlive: true,
        children: [
          { name: '查询', permission: 'system:role:query', type: MENU_TYPE.BUTTON, sort: 1, visible: true, keepAlive: false },
          { name: '新增', permission: 'system:role:create', type: MENU_TYPE.BUTTON, sort: 2, visible: true, keepAlive: false },
          { name: '修改', permission: 'system:role:update', type: MENU_TYPE.BUTTON, sort: 3, visible: true, keepAlive: false },
          { name: '删除', permission: 'system:role:delete', type: MENU_TYPE.BUTTON, sort: 4, visible: true, keepAlive: false },
        ],
      },
      {
        name: '菜单管理',
        permission: 'system:menu',
        type: MENU_TYPE.MENU,
        sort: 3,
        path: '/system/menu',
        icon: 'AppstoreOutlined',
        component: 'System/Menu',
        visible: true,
        keepAlive: true,
        children: [
          { name: '查询', permission: 'system:menu:query', type: MENU_TYPE.BUTTON, sort: 1, visible: true, keepAlive: false },
          { name: '新增', permission: 'system:menu:create', type: MENU_TYPE.BUTTON, sort: 2, visible: true, keepAlive: false },
          { name: '修改', permission: 'system:menu:update', type: MENU_TYPE.BUTTON, sort: 3, visible: true, keepAlive: false },
          { name: '删除', permission: 'system:menu:delete', type: MENU_TYPE.BUTTON, sort: 4, visible: true, keepAlive: false },
        ],
      },
      {
        name: '字典管理',
        permission: 'system:dict',
        type: MENU_TYPE.MENU,
        sort: 4,
        path: '/system/dict',
        icon: 'BookOutlined',
        component: 'System/Dict',
        visible: true,
        keepAlive: true,
        children: [
          { name: '查询', permission: 'system:dict:query', type: MENU_TYPE.BUTTON, sort: 1, visible: true, keepAlive: false },
          { name: '新增', permission: 'system:dict:create', type: MENU_TYPE.BUTTON, sort: 2, visible: true, keepAlive: false },
          { name: '修改', permission: 'system:dict:update', type: MENU_TYPE.BUTTON, sort: 3, visible: true, keepAlive: false },
          { name: '删除', permission: 'system:dict:delete', type: MENU_TYPE.BUTTON, sort: 4, visible: true, keepAlive: false },
        ],
      },
      {
        name: '部门管理',
        permission: 'system:dept',
        type: MENU_TYPE.MENU,
        sort: 5,
        path: '/system/dept',
        icon: 'ApartmentOutlined',
        component: 'System/Dept',
        visible: true,
        keepAlive: true,
        children: [
          { name: '查询', permission: 'system:dept:query', type: MENU_TYPE.BUTTON, sort: 1, visible: true, keepAlive: false },
          { name: '新增', permission: 'system:dept:create', type: MENU_TYPE.BUTTON, sort: 2, visible: true, keepAlive: false },
          { name: '修改', permission: 'system:dept:update', type: MENU_TYPE.BUTTON, sort: 3, visible: true, keepAlive: false },
          { name: '删除', permission: 'system:dept:delete', type: MENU_TYPE.BUTTON, sort: 4, visible: true, keepAlive: false },
        ],
      },
      {
        name: '岗位管理',
        permission: 'system:post',
        type: MENU_TYPE.MENU,
        sort: 6,
        path: '/system/post',
        icon: 'IdcardOutlined',
        component: 'System/Post',
        visible: true,
        keepAlive: true,
        children: [
          { name: '查询', permission: 'system:post:query', type: MENU_TYPE.BUTTON, sort: 1, visible: true, keepAlive: false },
          { name: '新增', permission: 'system:post:create', type: MENU_TYPE.BUTTON, sort: 2, visible: true, keepAlive: false },
          { name: '修改', permission: 'system:post:update', type: MENU_TYPE.BUTTON, sort: 3, visible: true, keepAlive: false },
          { name: '删除', permission: 'system:post:delete', type: MENU_TYPE.BUTTON, sort: 4, visible: true, keepAlive: false },
        ],
      },
    ],
  },
];

/**
 * 1. 创建管理员账号
 */
async function createAdminUser(): Promise<string> {
  console.log('🌱 开始创建管理员账号...\n');

  const username = 'admin';
  const password = 'admin123';

  // 检查管理员账号是否已存在
  const [existingUser] = await db
    .select()
    .from(sysUser)
    .where(eq(sysUser.username, username))
    .limit(1);

  if (existingUser) {
    console.log('⚠️  管理员账号已存在，跳过创建');
    console.log(`   账号：${username}`);
    console.log(`   ID：${existingUser.id}\n`);
    return existingUser.id;
  }

  // 加密密码
  const hashedPassword = await bcrypt.hash(password, 10);

  // 创建管理员账号
  const [admin] = await db
    .insert(sysUser)
    .values({
      username,
      password: hashedPassword,
      nickname: '系统管理员',
      status: 1,
      description: '默认管理员账号，请在生产环境中立即修改密码',
    })
    .returning();

  console.log('✅ 管理员账号创建成功！');
  console.log(`   账号：${username}`);
  console.log(`   密码：${password}`);
  console.log(`   ID：${admin.id}\n`);

  return admin.id;
}

/**
 * 2. 创建超级管理员角色
 */
async function createSuperAdminRole(): Promise<string> {
  console.log('🌱 开始创建超级管理员角色...\n');

  const roleCode = SYSTEM_ROLE.SUPER_ADMIN;
  const roleName = '超级管理员';

  // 检查角色是否已存在
  const [existingRole] = await db
    .select()
    .from(sysRole)
    .where(eq(sysRole.code, roleCode))
    .limit(1);

  if (existingRole) {
    console.log('⚠️  超级管理员角色已存在，跳过创建');
    console.log(`   角色编码：${roleCode}`);
    console.log(`   角色ID：${existingRole.id}\n`);
    return existingRole.id;
  }

  // 创建角色
  const [role] = await db
    .insert(sysRole)
    .values({
      code: roleCode,
      name: roleName,
      status: 1,
      description: '超级管理员角色，拥有系统所有权限，无需单独分配菜单权限',
    })
    .returning();

  console.log('✅ 超级管理员角色创建成功！');
  console.log(`   角色编码：${roleCode}`);
  console.log(`   角色名称：${roleName}`);
  console.log(`   角色ID：${role.id}\n`);

  return role.id;
}

/**
 * 3. 为管理员分配超级管理员角色
 */
async function assignRoleToAdmin(userId: string, roleId: string): Promise<void> {
  console.log('🌱 为管理员分配超级管理员角色...\n');

  // 检查是否已分配
  const [existing] = await db
    .select()
    .from(sysUserRole)
    .where(and(eq(sysUserRole.userId, userId), eq(sysUserRole.roleId, roleId)))
    .limit(1);

  if (existing) {
    console.log('⚠️  管理员已拥有超级管理员角色，跳过分配\n');
    return;
  }

  // 分配角色
  await db.insert(sysUserRole).values({
    userId,
    roleId,
    createdBy: userId,
  });

  console.log('✅ 角色分配成功！\n');
}

/**
 * 4. 递归创建菜单
 */
async function createMenus(
  menus: MenuData[],
  parentId: string | null = null,
  createdBy?: string
): Promise<string[]> {
  const menuIds: string[] = [];

  for (const menuItem of menus) {
    // 检查菜单是否已存在
    const [existingMenu] = await db
      .select()
      .from(sysMenu)
      .where(eq(sysMenu.permission, menuItem.permission))
      .limit(1);

    let menuId: string;

    if (existingMenu) {
      console.log(`⚠️  菜单 "${menuItem.name}" 已存在，跳过创建`);
      menuId = existingMenu.id;
    } else {
      // 创建菜单
      const [created] = await db
        .insert(sysMenu)
        .values({
          name: menuItem.name,
          permission: menuItem.permission,
          type: menuItem.type,
          sort: menuItem.sort,
          parentId,
          path: menuItem.path || null,
          icon: menuItem.icon || null,
          component: menuItem.component || null,
          visible: menuItem.visible,
          keepAlive: menuItem.keepAlive,
          createdBy,
        })
        .returning();

      menuId = created.id;
      console.log(`✅ 菜单 "${menuItem.name}" 创建成功 (ID: ${menuId})`);
    }

    menuIds.push(menuId);

    // 递归创建子菜单
    if (menuItem.children && menuItem.children.length > 0) {
      const childIds = await createMenus(menuItem.children, menuId, createdBy);
      menuIds.push(...childIds);
    }
  }

  return menuIds;
}

/**
 * 主函数：执行所有种子数据初始化
 */
async function seed() {
  console.log('========================================');
  console.log('🌱 开始初始化数据库种子数据');
  console.log('========================================\n');

  try {
    // 1. 创建管理员账号
    const adminUserId = await createAdminUser();

    // 2. 创建超级管理员角色
    const superAdminRoleId = await createSuperAdminRole();

    // 3. 为管理员分配超级管理员角色
    await assignRoleToAdmin(adminUserId, superAdminRoleId);

    // 4. 创建菜单
    console.log('🌱 开始创建菜单...\n');
    const menuIds = await createMenus(menuData, null, adminUserId);
    console.log(`\n✅ 共创建/检查了 ${menuIds.length} 个菜单（包括按钮权限）\n`);

    // 5. 输出总结信息
    console.log('========================================');
    console.log('✅ 数据库种子数据初始化完成！');
    console.log('========================================\n');
    console.log('📋 初始化信息：');
    console.log(`   管理员账号：admin`);
    console.log(`   管理员密码：admin123`);
    console.log(`   管理员角色：超级管理员 (super_admin)`);
    console.log(`   菜单数量：${menuIds.length} 个（包括按钮权限）`);
    console.log(`   ⚠️  提示：超级管理员拥有所有权限，无需单独分配菜单权限\n`);
    console.log(`   ⚠️  警告：请在生产环境中立即修改管理员密码！\n`);
  } catch (error) {
    console.error('❌ 数据库种子数据初始化失败：', error);
    throw error;
  }
}

// 执行种子数据初始化
seed()
  .then(() => {
    console.log('✅ 种子数据脚本执行完成');
    process.exit(0);
  })
  .catch((error) => {
    console.error('❌ 种子数据脚本执行失败：', error);
    process.exit(1);
  });


